<template>
  <div class="employees-container">
    <div class="app-container">
      <HeadTool>
        <div class="btns" slot="after-box">
          <el-button type="success" size="small" @click="exportTo">
            导出
          </el-button>
          <el-button
            type="primary"
            @click="
              $router.push({ path: '/import', query: { type: 'employees' } })
            "
            size="small"
            >导入</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="showDialog = true"
            >新增员工</el-button
          >
        </div>
      </HeadTool>

      <el-card class="card">
        <el-table border :data="tableData">
          <el-table-column
            width="150px"
            label="序号"
            type="index"
          ></el-table-column>
          <el-table-column prop="staffPhoto" width="120px" label="头像">
            <template slot-scope="{ row }">
              <img
                style="width:60px;"
                v-imgerror="photo"
                :src="row.staffPhoto"
                @click="showQrCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column
            prop="mobile"
            width="180px"
            label="手机号"
          ></el-table-column>
          <el-table-column prop="workNumber" label="工号"></el-table-column>
          <el-table-column
            prop="formOfEmployment"
            width="150px"
            label="聘用形式"
          >
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            width="150px"
            label="部门"
          ></el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" width="150px">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" width="120px" label="状态">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="230px">
            <div
              slot-scope="{ row }"
              style="display:flex;justify-content:space-between"
            >
              <el-link
                type="primary"
                @click="
                  $router.push({
                    path: '/employees/details',
                    query: { id: row.id }
                  })
                "
                >查看</el-link
              >
              <el-link type="primary">转正</el-link>
              <el-link type="primary">调岗</el-link>
              <el-link type="primary">离职</el-link>
              <el-link type="primary" @click="showRole(row.id)">角色</el-link>
              <el-link
              v-if="checkPoint('aa')"
               @click="delEmp(row.id)" type="primary">删除</el-link>
            </div>
          </el-table-column>
        </el-table>

        <el-pagination
          :page-size="pageInfo.size"
          :current-page="pageInfo.page"
          :total="pageInfo.total"
          @current-change="changeOut"
          style="text-align:right"
          layout="total, prev, pager, next"
        />
      </el-card>
      <addEmp :showDialog.sync="showDialog" />
      <el-dialog :visible.sync="showCodeDialog" title="二维码">
        <!-- 二维码 -->
        <el-row type="flex" justify="center">
          <canvas ref="canvas"></canvas>
        </el-row>
      </el-dialog>
      <role-setting
        ref="roleSet"
        :showRoleDialog.sync="showRoleDialog"
        :userId="currentId"
      />
    </div>
  </div>
</template>

<script>
import constant from "@/api/constant/employees";
import addEmp from "./componets/add-emp.vue";
import { getEmpList, delEmp } from "@/api/employees";
// 导入日期格式处理
import { formatDate } from "@/filters";
import qrCode from "qrcode";
import roleSetting from "./componets/role-setting.vue";
export default {
  name: "employees",

  data() {
    return {
      // 控制分配角色对话框的显示和隐藏
      showRoleDialog: false,
      currentId: "",
      showCodeDialog: false,
      showDialog: false,
      tableData: [],
      photo: require("@/assets/common/head.jpg"),
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async showRole(id) {
      // 再把id赋值给子组件
      this.currentId = id;
      // 让对话框显示
      this.showRoleDialog = true;
      // 调用子组件里的方法获取当前用户的数据
      await this.$refs.roleSet.getUserProfile(id);
    },
    // 图片点击事件
    showQrCode(val) {
      if (val) {
        this.showCodeDialog = true;
        this.$nextTick(() => {
          qrCode.toCanvas(this.$refs.canvas, val);
        });
      } else {
        this.$message.warning("此用户没有头");
      }
    },
    // 导出事件
    async exportTo() {
      let res = await getEmpList({
        page: 1,
        size: this.pageInfo.total
      });
      let list = res.data.rows;
      const headers = {
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName"
      };
      let keys = Object.keys(headers);
      let BigArr = list.map(item => {
        let arr = [];
        for (let key in headers) {
          let engKey = headers[key];
          if (key == "入职日期" || key == "转正日期") {
            let res = formatDate(item[engKey]);
            arr.push(res);
          } else if (key == "聘用形式") {
            let str = item[engKey] == 1 ? "正式" : "未知";
            arr.push(str);
          } else {
            arr.push(item[engKey]);
          }
        }
        return arr;
      });

      // 懒加载使用插件的办法
      import("@/vendor/Export2Excel").then(excel => {
        excel.export_json_to_excel({
          header: keys, //表头 必填
          data: BigArr, //具体数据 必填
          filename: "我爱你", //非必填
          autoWidth: true, //非必填
          bookType: "xlsx" //非必填
        });
      });
    },
    async getList() {
      let res = await getEmpList(this.pageInfo);
      this.tableData = res.data.rows;
      this.tableData.forEach(item => {
        item.enableState = item.enableState == 1 ? true : false;
      });
      this.pageInfo.total = res.data.total;
    },
    async delEmp(id) {
      try {
        await this.$confirm("确认要删除吗？");
        if (this.tableData.length == 1 && this.pageInfo.page != 1) {
          this.pageInfo.page--;
        }
        await delEmp(id);
        this.$message.success("删除成功");
        this.getList();
      } catch (error) {
        return;
      }
    },
    changeOut(page) {
      this.pageInfo.page = page;
      this.getList();
    }
  },
  filters: {
    formatHireType(val) {
      let list = constant.hireType.filter(item => item.id == val);
      return list[0] ? list[0].value : "未知";
    }
  },
  components: {
    addEmp,
    roleSetting
  }
};
</script>

<style lang="scss" scoped>
.employees-container {
  ::v-deep .el-dialog {
    .el-dialog__header {
      background-color: #90f;
    }
  }
}
</style>
